<template>
  <div>
    <a-modal
      v-model:visible="state.showSlaConfigModal"
      title="SLA配置"
      :footer="null"
      @cancel="closeModal"
      :destroy-on-close="true"
      width="30vw"
    >
      <a-space style="justify-content: flex-end; width: 100%">
        <a-button
          size="small"
          type="primary"
          @click="createSlaConfig"
          ref="createSlaConfigBtn"
          :disabled="state.createSlaConfigBtnDisabled"
          :loading="state.loadingCreateSlaConfigBtn"
        >
          新增
        </a-button>
      </a-space>
      <div class="sla-config-table">
        <remote-table
          v-model:value="state.slaTableData"
          ref="slaConfigTable"
          :show-selection="false"
          :has-export="false"
          :show-setting="false"
          :has-refresh="false"
          :has-reset="false"
          :has-action="true"
          :has-paginate="false"
          :row-key="(record, index) => index"
          :columns="updateNodeColumns"
          @change="selectSlaChange"
          :sy="300"
          :y="300"
          interface-u-r-l="/todo/SLA/page"
          :column-width="{
            task: 450
          }"
        >
          <template v-slot:action="{ record }">
            <a-space>
              <a class="table-btns" @click="updateSlaConfig(record)"> 编辑 </a>
              <a-popconfirm
                title="是否删除该SLA配置?"
                ok-text="是"
                cancel-text="否"
                @confirm="deleteSlaConfig(record)"
                @cancel="deleteSlaConfigCancel"
              >
                <a class="table-btns" href="javascript:void(0)"> 删除 </a>
              </a-popconfirm>
            </a-space>
          </template>
        </remote-table>
      </div>
    </a-modal>
    <a-modal
      v-model:visible="state.showCreateSlaConfigModal"
      title="SLA配置"
      :footer="null"
      @cancel="state.showCreateSlaConfigModal = false"
      :destroy-on-close="true"
      width="30vw"
    >
      <a-form layout="inline">
        <a-row class="sla-type-form-item" :gutter="16">
          <a-col class="gutter-row" :span="24">
            <a-form-item label="流程类型：" style="width: 100%; display: flex">
              <a-select
                allow-clear
                v-model:value="state.slaType"
                placeholder="请选择"
                style="width: 100%"
              >
                <a-select-option
                  v-for="item in props.slaTypeOptions"
                  :key="item.todoBusinessType"
                  :value="item.todoBusinessType"
                  :disabled="item.disabled"
                >
                  {{ item.todoTypeText }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col class="gutter-row" :span="12">
            <a-form-item label="告警时长：">
              <a-input-number
                v-model:value="state.alarmDuration"
                :min="0"
                :max="1000000000"
                :precision="0"
                style="--content: '小时'"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="超时时长：">
              <a-input-number
                v-model:value="state.timeoutDuratiojn"
                :min="0"
                :max="1000000000"
                :precision="0"
                style="--content: '小时'"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="text-center mt20">
        <a-space>
          <a-button
            type="primary"
            @click="confirmSlaConfigHandler"
            :loading="state.loadingConfirmAllocationBtn"
          >
            确定
          </a-button>
          <a-button @click="state.showCreateSlaConfigModal = false">
            取消
          </a-button>
        </a-space>
      </div>
    </a-modal>
  </div>
</template>
<script setup>
import {
  todo_sla_config_add,
  todo_sla_config_update,
  todo_sla_delete_post
} from 'server/modules/7537'
import {
  defineProps,
  defineEmits,
  reactive,
  toRef,
  watch,
  nextTick,
  ref
} from 'vue'

import { message } from 'ant-design-vue'

const props = defineProps(['showSlaConfigModal', 'slaTypeOptions'])

const emit = defineEmits(['closeModal'])

const state = reactive({
  showSlaConfigModal: false,
  createSlaConfigBtnDisabled: false,
  loadingCreateSlaConfigBtn: false,
  showCreateSlaConfigModal: false,
  loadingConfirmAllocationBtn: false,
  slaTableId: null,
  slaType: [],
  alarmDuration: null,
  timeoutDuratiojn: null,
  slaTableData: []
})

const slaConfigTable = ref(null)

state.showSlaConfigModal = toRef(props, 'showSlaConfigModal')

const updateNodeColumns = reactive([
  {
    title: '流程类型',
    dataIndex: 'todoTypeText',
    width: 'auto',
    key: 'todoTypeText'
  },
  {
    title: '告警时长（H）',
    dataIndex: 'alarmDuration',
    width: 'auto',
    key: 'alarmDuration'
  },
  {
    title: '超时时长（H）',
    dataIndex: 'timeoutDuratiojn',
    width: 'auto',
    key: 'timeoutDuratiojn'
  },
  {
    title: '操作',
    dataIndex: 'operator',
    key: 'operator',
    width: '180px',
    align: 'center',
    slots: { customRender: 'action' }
  }
])
watch(
  () => props.showSlaConfigModal,
  val => {
    if (val) {
      state.loadingCreateSlaConfigBtn = true
      // 禁用
      nextTick(() => {
        // 禁用
        let unwatch = null
        unwatch = watch(
          () => state.slaTableData,
          val => {
            if (val.length > 0) {
              let count = 0
              props.slaTypeOptions.forEach(item1 => {
                try {
                  state.slaTableData.forEach(item2 => {
                    if (item2.todoBusinessType === item1.todoBusinessType) {
                      item1.disabled = true
                      count++
                      throw new Error('已存在')
                    } else {
                      item1.disabled = false
                    }
                  })
                  // eslint-disable-next-line no-empty
                } catch (error) {}
              })
              if (count === props.slaTypeOptions.length) {
                state.createSlaConfigBtnDisabled = true
              } else {
                state.createSlaConfigBtnDisabled = false
              }
              state.loadingCreateSlaConfigBtn = false
              if (unwatch) unwatch()
            }
          },
          { deep: true, immediate: true }
        )
      })
    }
  }
)
watch(
  () => state.showCreateSlaConfigModal,
  val => {
    if (!val) {
      state.slaTableId = null
      state.slaType = []
      state.alarmDuration = null
      state.timeoutDuratiojn = null
    }
  }
)
function createSlaConfig() {
  state.showCreateSlaConfigModal = true
}
function updateSlaConfig(record) {
  state.slaTableId = record.id
  state.slaType = record.todoBusinessType
  state.alarmDuration = record.alarmDuration
  state.timeoutDuratiojn = record.timeoutDuratiojn
  state.showCreateSlaConfigModal = true
}

function deleteSlaConfig(record) {
  state.loadingConfirmAllocationBtn = true
  todo_sla_delete_post({
    id: record.id
  })
    .then(({ success, retInfo, data }) => {
      if (success) {
        message.success(data)
        state.createSlaConfigBtnDisabled = false
        slaConfigTable.value.refresh()
        let unwatch = null
        unwatch = watch(state.slaTableData, val => {
          if (val.length > 0) {
            const element = document.querySelector(
              '.sla-config-table div.ant-table-body'
            )
            if (element.scrollHeight > element.clientHeight) {
              const tableHeader = document.querySelector(
                '.sla-config-table div.ant-table-header'
              )
              tableHeader.style.overflowY = 'scroll'
            } else {
              const tableHeader = document.querySelector(
                '.sla-config-table div.ant-table-header'
              )
              tableHeader.style.overflowY = 'hidden'
            }
            props.slaTypeOptions.forEach(item1 => {
              try {
                state.slaTableData.forEach(item2 => {
                  if (item2.todoBusinessType === item1.todoBusinessType) {
                    item1.disabled = true
                    throw new Error('已存在')
                  } else {
                    item1.disabled = false
                  }
                })
              } catch (error) {
                console.log(error)
              }
            })
            if (unwatch) unwatch()
          }
        })
      } else {
        message.error(retInfo)
      }
    })
    .finally(() => {
      state.loadingConfirmAllocationBtn = false
    })
}

function deleteSlaConfigCancel() {
  message.info('取消删除')
}

async function confirmSlaConfigHandler() {
  state.loadingConfirmAllocationBtn = true
  let requestUrl = todo_sla_config_add
  if (state.slaTableId) {
    requestUrl = todo_sla_config_update
  }
  console.log(state.slaType, props.slaTypeOptions)
  const { success, data } = await requestUrl({
    id: state.slaTableId,
    todoBusinessType: state.slaType,
    todoTypeCode: props.slaTypeOptions.find(
      item => item.todoBusinessType === state.slaType
    ).todoTypeCode,
    todoTypeText: function () {
      for (const item of props.slaTypeOptions) {
        if (item.todoBusinessType === state.slaType) {
          return item.todoTypeText
        }
      }
    }.bind(this)(),
    alarmDuration: state.alarmDuration,
    timeoutDuratiojn: state.timeoutDuratiojn
  })
  state.loadingConfirmAllocationBtn = false
  if (success) {
    message.success(data)
    let count = 0
    slaConfigTable.value.refresh()
    let unwatch = null
    unwatch = watch(state.slaTableData, val => {
      if (val.length > 0) {
        props.slaTypeOptions.forEach(item1 => {
          try {
            state.slaTableData.forEach(item2 => {
              if (item2.todoBusinessType === item1.todoBusinessType) {
                item1.disabled = true
                count++
                throw new Error('已存在')
              } else {
                item1.disabled = false
              }
            })
            // eslint-disable-next-line no-empty
          } catch (error) {}
        })
        if (unwatch) unwatch()
        if (count === props.slaTypeOptions.length) {
          state.createSlaConfigBtnDisabled = true
        } else {
          state.createSlaConfigBtnDisabled = false
        }
      }
    })
  }
  state.showCreateSlaConfigModal = false
}
function closeModal() {
  emit('closeModal')
}
</script>
<style lang="scss" scoped>
.sla-type-form-item .ant-form-item :deep() {
  width: 100%;
  display: flex;

  .ant-form-item-label {
    line-height: 39.9999px;
  }
  .ant-select-selector {
    border-radius: 4px;
  }
  .ant-input-number {
    display: inline-table;
    border-radius: 4px;
    width: 100%;
    .ant-input-number-handler-wrap {
      display: none;
    }
    &::after {
      content: var(--content);
      color: #909399;
      background-color: #f5f7fa;
      vertical-align: middle;
      display: table-cell;
      position: relative;
      border-radius: 4px;
      border-left: 0;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
      padding: 0 20px;
      width: 1px;
      white-space: nowrap;
    }
  }
  .ant-form-item-control-wrapper {
    flex-grow: 1;
  }
}
.text-center :deep() {
  text-align: center;
}
</style>
